package terra.managers;

import terra.network.Connections;
import terra.network.packet.server.TimeInfo;

public class DayNightManager implements Runnable {

	public static byte DAY = 0;
	public static byte DAWN = 1;
	public static byte NIGHT = 2;
	public static byte DUSK = 3;
	public static float DAY_LIGHT = 1f;
	public static float NIGHT_LIGHT = 0.1f;
	public static float DUSK_LIGHT = 0.4f;
	public static float DAWN_LIGHT = 0.4f;
	public static long DAY_TIME = 120 * 1000L;
	public static long NIGHT_TIME = 30 * 1000L;
	public static long DUSK_TIME = 10 * 1000L;
	public static long DAWN_TIME = 10 * 1000L;
	public static long CHANGE_LIGHT_TIME = 10 * 1000L;
	private static DayNightManager instance;

	public float lightIntense = NIGHT_LIGHT;
	public byte current = 2;
	public long nextChangeTime = CHANGE_LIGHT_TIME;
	TimeInfo timeInfo = new TimeInfo();

	public DayNightManager() {
		init();
	}

	public void init() {
		Thread t = new Thread(this, "DayNightManager Thread");
		t.setPriority(Thread.MIN_PRIORITY);
		t.start();
		current = NIGHT;
		lightIntense = getLightIntenseForDayState(current);
		nextChangeTime = System.currentTimeMillis()
				+ getTimeForDayState(current);
		System.out.println("DayNightManager : initialized");
	}

	long getTimeForDayState(int dayState) {
		if (dayState == DAY)
			return DAY_TIME;
		else if (dayState == NIGHT)
			return NIGHT_TIME;
		else if (dayState == DAWN)
			return DAWN_TIME;
		else
			return DUSK_TIME;
	}

	float getLightIntenseForDayState(int dayState) {
		if (dayState == DAY)
			return DAY_LIGHT;
		else if (dayState == NIGHT)
			return NIGHT_LIGHT;
		else if (dayState == DAWN)
			return DAWN_LIGHT;
		else
			return DUSK_LIGHT;
	}

	@Override
	public void run() {
		while (true) {
			if (nextChangeTime < System.currentTimeMillis()) {
				current++;
				if (current > DUSK)
					current = 0;
				nextChangeTime = System.currentTimeMillis()
						+ getTimeForDayState(current);
			}

			if (lightIntense != getLightIntenseForDayState(current)) {
				if (lightIntense > getLightIntenseForDayState(current))
					lightIntense -= 0.005f;
				else
					lightIntense += 0.005f;
			}
			timeInfo.time = current;
			timeInfo.lightIntense = lightIntense;
			Connections.broadcast(timeInfo);
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public static DayNightManager getInstance() {
		if (instance == null)
			instance = new DayNightManager();
		return instance;
	}

}
